package cvi.com.reader.activity;

import android.content.Intent;
import android.content.pm.PackageManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.TabLayout;
import android.util.Log;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.orhanobut.hawk.Hawk;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadmoreListener;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import cvi.com.reader.R;
import cvi.com.reader.adapter.MusicListAdapter;
import cvi.com.reader.base.BaseActivity;
import cvi.com.reader.bean.FlagBean;
import cvi.com.reader.bean.MusicCategoriesBean;
import cvi.com.reader.bean.MusicListDataBean;
import cvi.com.reader.bean.constant;
import cvi.com.reader.network.DefaultObserver;
import cvi.com.reader.network.NetWorkManager;
import cvi.com.reader.tool.refresh.CustomRefreshFooter;
import cvi.com.reader.tool.refresh.CustomRefreshHeader;
import cvi.com.reader.widgets.MultiStateView;
import cvi.com.reader.widgets.MyListView;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by 梅涛 on 2020/8/3.
 * 背景音乐
 */

public class BackgroundMusicActivity extends BaseActivity implements View.OnClickListener, MusicListAdapter.PlayerClickInterface {
    @BindView(R.id.back)
    LinearLayout back;
    @BindView(R.id.tittle)
    TextView tittle;
    @BindView(R.id.right_icon)
    LinearLayout rightIcon;
    @BindView(R.id.first_tabLayout)
    TabLayout firstTabLayout;
    @BindView(R.id.second_tabLayout)
    TabLayout secondTabLayout;
    @BindView(R.id.aa)
    LinearLayout aa;
    @BindView(R.id.mylistview)
    MyListView myListView;
    @BindView(R.id.no_data)
    TextView noData;
    @BindView(R.id.stateView)
    MultiStateView stateView;
    @BindView(R.id.smartRefreshLayout_home)
    SmartRefreshLayout smartRefreshLayout;
    //分类集合
    private List<MusicCategoriesBean.DataBean> dataBeanList = new ArrayList<>();
    //列表集合
    private List<MusicListDataBean.DataBean> musicListDataBeans = new ArrayList<>();
    private int first_id = -1;
    private MusicListAdapter musicListAdapter = null;
    private MediaPlayer mediaPlayer = new MediaPlayer();//实例化MediaPlayer类
    private FlagBean flagBean = new FlagBean();

    @Override
    protected int getLayoutId() {
        return R.layout.activity_background_music;
    }

    @Override
    protected void initView() {
        initSmartRefreshLayout();
        stateView.getBackground().setAlpha(153);
        back.setOnClickListener(this);
        tittle.setText("背景音乐");
    }

    @Override
    protected void initData() {
        //获取音乐背景分类
        getBGMCategories();
    }

    private void initMediaPlayer(String url) {
        Uri uri = Uri.parse(url);//网络中的音乐文件
        try {
            mediaPlayer.setDataSource(this, uri);//音乐文件路径
            mediaPlayer.prepare();//资源文件准备
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void getBGMCategories() {
        //绑定生命周期,获取宫格数据
        NetWorkManager.getInstance().getNetWorkApiService().getBGMCategorData().compose(this.<JSONObject>bindToLifecycle())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new DefaultObserver<JSONObject>(BackgroundMusicActivity.this) {
                    @Override
                    protected void onSuccess(JSONObject response) {
                        setCategories(response);
                    }
                });
    }

    //初始化下拉刷新控件
    private void initSmartRefreshLayout() {
        smartRefreshLayout.setEnableLoadmore(false);
        smartRefreshLayout.setRefreshHeader(new CustomRefreshHeader(BackgroundMusicActivity.this));
        smartRefreshLayout.setRefreshFooter(new CustomRefreshFooter(BackgroundMusicActivity.this, "加载中…"));
        smartRefreshLayout.setEnableScrollContentWhenLoaded(true);//是否在加载完成时滚动列表显示新的内容
        smartRefreshLayout.setEnableFooterFollowWhenLoadFinished(true);
        smartRefreshLayout.setOnRefreshLoadmoreListener(new OnRefreshLoadmoreListener() {
            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
                //  presenter.onLoadMore();
            }

            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                musicListDataBeans.clear();
                getBGMList(first_id);
            }
        });

    }

    private void setCategories(JSONObject response) {
        firstTabLayout.removeAllTabs();
        JSONArray array = response.getJSONArray("data");
        for (int i = 0; i < array.size(); i++) {
            JSONObject object = (JSONObject) array.get(i);     //将array中的数据进行逐条转换
            MusicCategoriesBean.DataBean dataBean = (MusicCategoriesBean.DataBean) JSONObject.toJavaObject(object, MusicCategoriesBean.DataBean.class);  //通过JSONObject.toBean()方法进行对象间的转换
            dataBeanList.add(dataBean);
        }

        for (int i = 0; i < dataBeanList.size(); i++) {
            TabLayout.Tab tab = firstTabLayout.newTab();
            tab.setText(dataBeanList.get(i).getName());
            if (i == 0) {
                //初始化界面
                first_id = dataBeanList.get(i).getId();
                Log.d("sdsafdfa", "!!!!!!" + first_id);
                //获取音乐背景某一分类列表并初始化界面
                getBGMList(first_id);
                firstTabLayout.addTab(tab, true);
            } else {
                firstTabLayout.addTab(tab, false);
            }
        }
        firstTabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                for (int i = 0; i < dataBeanList.size(); i++) {
                    if (tab.getText().toString().trim().equals(dataBeanList.get(i).getName())) {
                        first_id = dataBeanList.get(i).getId();
                        stateView.setViewState(MultiStateView.VIEW_STATE_LOADING);
                        //获取音乐背景某一分类列表
                        getBGMList(first_id);
                    }
                }
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
    }

    private void getBGMList(final int categoriesId) {

        //绑定生命周期,获取宫格数据
        NetWorkManager.getInstance().getNetWorkApiService().getBGMListData(categoriesId).compose(this.<JSONObject>bindToLifecycle())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new DefaultObserver<JSONObject>(BackgroundMusicActivity.this) {
                    @Override
                    protected void onSuccess(JSONObject response) {
                        setListData(response, categoriesId);
                        stateView.setViewState(MultiStateView.VIEW_STATE_CONTENT);
                        smartRefreshLayout.finishRefresh(true);
                    }
                });
    }

    private void setListData(JSONObject response, int categoriesId) {
        musicListDataBeans.clear();
        JSONArray array = response.getJSONArray("data");
        for (int i = 0; i < array.size(); i++) {
            JSONObject object = (JSONObject) array.get(i);     //将array中的数据进行逐条转换
            MusicListDataBean.DataBean dataBean = (MusicListDataBean.DataBean) JSONObject.toJavaObject(object, MusicListDataBean.DataBean.class);  //通过JSONObject.toBean()方法进行对象间的转换
            musicListDataBeans.add(dataBean);
        }
        if (0 == musicListDataBeans.size()) {
            noData.setVisibility(View.VISIBLE);
        } else {
            noData.setVisibility(View.GONE);
            musicListAdapter = new MusicListAdapter(BackgroundMusicActivity.this, musicListDataBeans, categoriesId);
            myListView.setAdapter(musicListAdapter);
            musicListAdapter.setOnPlayerClickInterface(this);
            musicListAdapter.notifyDataSetChanged();
        }

    }

    @Override
    protected void extrasDoSome(Bundle extras) {

    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.back:
                finish();
                break;

        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    @Override
    public void onPlayerClick(String url) {
        Log.d("dsffff", "222223333" + url);
        Uri uri = Uri.parse(url);//网络中的音乐文件
        try {
            mediaPlayer.reset();
            mediaPlayer.setDataSource(this, uri);//音乐文件路径
            mediaPlayer.prepare();//资源文件准备
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (!mediaPlayer.isPlaying()) {
            mediaPlayer.start();//播放
        }
        // musicListAdapter.notifyDataSetChanged();
    }

    @Override
    public void onPauseClick(String url) {
        Log.d("dsffff", "11111122222" + url);
        if (mediaPlayer.isPlaying()) {
            mediaPlayer.pause();//暂停
        }
        // musicListAdapter.notifyDataSetChanged();
    }

    @Override
    public void onApplyMusic(String url, int musicId, String musicName, String author) {
        Intent data = new Intent();
        data.putExtra("musicId", musicId);
        data.putExtra("musicName", musicName);
        data.putExtra("author", author);
        data.putExtra("url", url);
        setResult(constant.WORKS_DETAIL_CODE, data);
        finish();

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case 1:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // initMediaPlayer();
                } else {
                    Toast.makeText(this, "拒绝权限无法继续使用程序", Toast.LENGTH_SHORT).show();
                    finish();
                }
                break;
            default:
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //清除列表播放暂停标识
        if (Hawk.contains("flagBean")) {
            Hawk.delete("flagBean");
        }

        if (mediaPlayer != null) {
            mediaPlayer.stop();
            mediaPlayer.release();
        }
    }
}

